package com.shinemo.mpush.alloc.handler;

import com.mpush.api.chat.MessageNotification;
import com.mpush.api.chat.MessageNotificationDto;
import com.mpush.api.protocol.PushType;
import com.mpush.api.push.*;
import com.mpush.tools.Jsons;
import com.shinemo.mpush.alloc.common.ResultCode;
import com.shinemo.mpush.alloc.http.HttpRequest;
import com.shinemo.mpush.alloc.http.HttpResponse;
import com.shinemo.mpush.alloc.service.MesIdService;
import com.shinemo.mpush.alloc.vo.BaseResponse;
import com.shinemo.mpush.alloc.vo.MessageNotificationPushResponse;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public class MessageNotificationHandler implements HttpHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private PushSender pushSender = null;
    private MesIdService mesIdService = null;


    public MessageNotificationHandler(PushSender pushSender, MesIdService mesIdService) {
        this.pushSender = pushSender;
        this.mesIdService = mesIdService;
    }

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {

        BaseResponse response = new MessageNotificationPushResponse();

        try {
            String body = HttpRequest.getBody(httpExchange);
            logger.info("接收到的消息:{}", body);
            Map<String, Object> params = HttpRequest.toMap(body);
            response = this.sendPush(params);
        } catch (Exception e) {
            logger.error("", e);
            response.setCode(ResultCode.INTERNAL_SERVER_ERROR.getCode());
            response.setMes("内部错误");
        }

        HttpResponse.writeJson(httpExchange, Jsons.toJson(response));
    }

    private BaseResponse sendPush(Map<String, Object> params) {

        MessageNotificationDto dto = Jsons.fromJson(Jsons.toJson(params), MessageNotificationDto.class);
        MessageNotification messageNotification = MessageNotification.from(dto);


        PushContent pushContent = new PushContent(PushType.MESSAGE_NOTIFICATION, Jsons.toJson(messageNotification));

        PushMsg pushMsg = PushMsg.build(MsgType.NOTIFICATION_AND_MESSAGE, Jsons.toJson(pushContent));
        pushMsg.setMsgId(mesIdService.createMesId());

        pushSender.send(PushContext.build(pushMsg).setUserId(dto.getUserId()));

        BaseResponse response = new BaseResponse();
        response.setCode(ResultCode.SUCCESS.getCode());
        response.setMes("成功");
        return response;
    }


}
